import React, {useCallback, useEffect, useState} from "react"
import {Button, DatePicker, Form, Input, Select, Space, Table} from "antd";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import {getAllMarketsOnlyICanSee} from "../../apis/MarketsApi";
import FormDrawer from "../../components/FormDrawer";
import DataPageLayout from "../../components/DataPageLayout";
import AuthorizationResource from "../../components/AuthorizationResource";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    createMarketSaleDocument,
    deleteMarketSaleDocument,
    getAllMarketSaleDocumentCreatedEmployees,
    MarketSaleDocumentStatus,
    marketSaleDocumentStatuses,
    marketSaleDocumentStatusMap,
    QueryMarketSaleDocumentResponse,
    queryMarketSaleDocuments
} from "../../apis/MarketSaleDocumentApi";
import {Pageable} from "../../utils/Page";
import {
    AntdTableColumnRenders,
    mergePaginationAndPageable,
    useTableFilterDateRangeColumnProps
} from "../../utils/AntdTableUtils";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../../components/LoadableButton";
import {useGlobalStyle} from "../../global.style";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Dayjs} from "dayjs";
import {DATE_WITH_TIME_FORMATER, YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";

export interface pageProps {

}

export interface MarketSaleDocumentFormData {
    marketId: number
    note?: string
    yearAndMonth:string
}


const MarketSaleDocumentPage: React.FC<pageProps> = (props) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketSaleDocumentResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [marketIds, setMarketIds] = useState<number[]>(urlSearchParams.getAll("marketIds").map(it => parseInt(it)))
    const [createdByIds, setCreatedByIds] = useState<number[]>([])


    const [markets, setMarkets] = useState<Array<NumberIdAndName>>([])
    useEffect(() => {
        getAllMarketsOnlyICanSee().then(response => {
            setMarkets(response.data)
        })
    }, []);

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [status, setStatus] = useState<MarketSaleDocumentStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryMarketSaleDocuments({
            marketIds,
            createdByIds: createdByIds,
            startDate: startDate ? LocalDate.parse(startDate).toString() : undefined,
            endDate: endDate ? LocalDate.parse(endDate).toString() : undefined,
            status,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), marketIds, createdByIds, startDate, endDate, status])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllMarketSaleDocumentCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);

    function buildFormItems() {
        return <>
            <Form.Item label={"卖场"} name="marketId" rules={[{required: true}]}>
                <Select placeholder={"选择卖场"} showSearch options={markets.map(it => ({
                    label: it.name,
                    value: it.id,
                }))} filterOption={(inputValue, option) => {
                    return (option?.label as string).toUpperCase().includes(inputValue.toUpperCase())
                }}/>
            </Form.Item>
            <Form.Item label={"备注"} name={"note"}>
                <Input.TextArea/>
            </Form.Item>
            <Form.Item label={"时间范围"} name={"yearAndMonth"} rules={[{required: true,}]}>
                <DatePicker.MonthPicker/>
            </Form.Item>
        </>
    }

    let globalStyle = useGlobalStyle();
    let navigate = useNavigate();
    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["卖场_销售单_开单"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>创建</Button>
        </AuthorizationResource>}>
            <Table<QueryMarketSaleDocumentResponse> className={globalStyle.rowClickableTable} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/markets/saleDocuments/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setMarketIds(filters["market.name"] as number[])
                setCreatedByIds(filters["createdBy.name"] as number[])
                let filter = filters["status"] as unknown as MarketSaleDocumentStatus[];
                setStatus(filter ? filter[0] : undefined)
            }}>
                <Table.Column<QueryMarketSaleDocumentResponse> filteredValue={marketIds} dataIndex={["market", "name"]}
                                                               title={"卖场"}
                                                               filters={markets.map(market => {
                                                                   return {
                                                                       text: market.name,
                                                                       value: market.id,
                                                                   }
                                                               })} render={(_, record) => {
                    return record.market.name
                }}/>
                <Table.Column dataIndex={"createdDateTime"} title={"创建时间"}
                              {...useTableFilterDateRangeColumnProps<QueryMarketSaleDocumentResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? value[0].format() : undefined)
                                      setEndDate(value ? value[1].format() : undefined)
                                  }
                              })}
                              render={(value) => value.format(DATE_WITH_TIME_FORMATER)}/>
                <Table.Column dataIndex={"startDateTime"} title={"开始时间"}
                              render={AntdTableColumnRenders.dateTimeStringColumnRender}/>
                <Table.Column dataIndex={"endDateTime"} title={"结束时间"}
                              render={AntdTableColumnRenders.dateTimeStringColumnRender}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column<QueryMarketSaleDocumentResponse> dataIndex={"status"}
                                                               filteredValue={status ? [status] : []}
                                                               title={"状态"}
                                                               key={"status"}
                                                               filterMultiple={false}
                                                               filters={marketSaleDocumentStatuses.map(it => ({
                                                                   text: marketSaleDocumentStatusMap[it],
                                                                   value: it
                                                               }))} render={(value, record) => {
                    return marketSaleDocumentStatusMap[value]
                }}/>
                <Table.Column dataIndex={["createdBy", "name"]} title={"创建人"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
                <Table.Column<QueryMarketSaleDocumentResponse> title={"操作"} render={(_, record) => {
                    return <>
                        {employeeAuthorizationStore.hasAuthority("卖场_销售单_删除") && record.status === "WAIT_SUBMIT" &&
                            <LoadableButton danger type={"text"} onClick={async (event) => {
                                event.stopPropagation()
                                await deleteMarketSaleDocument(record.id)
                                query()
                            }}><DeleteOutlined/>删除</LoadableButton>}
                    </>
                }}/>
            </Table>
        </DataPageLayout>
        <FormDrawer<MarketSaleDocumentFormData> onClose={() => setOpenAddDrawer(false)}
                                                title={"创建销售单"}
                                                onConfirm={async (values) => {
                                                    const yearAndMonth = values.yearAndMonth
                                                    const yearAndMonthArray = yearAndMonth.split("-")
                                                    return createMarketSaleDocument(values.marketId, {
                                                        note: values.note,
                                                        year: Number(yearAndMonthArray[0]),
                                                        month: Number(yearAndMonthArray[1]),
                                                    }).then(response => {
                                                        setOpenAddDrawer(false)
                                                        navigate(`/markets/saleDocuments/${response.data}`)
                                                        query()
                                                    })
                                                }}
                                                open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(MarketSaleDocumentPage, "markets/accounts/saleDocuments", "卖场销售")
